<template>
  <div class="container">
    <el-dialog :title="title" :visible.sync="dialogVisible" width="40%" :before-close="handleClose">
      <el-form :model="formData" ref="ruleForm" :rules="rules">
        <el-form-item prop="subjectName" label="学科名称">
          <el-input placeholder="请输入学科" v-model.trim="formData.subjectName"></el-input>
        </el-form-item>
        <el-form-item prop="isFrontDisplay" label="是否显示">
          <el-switch v-model="formData.isFrontDisplay"></el-switch>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="$emit('update:visible', false)">取 消</el-button>
        <el-button type="primary" @click="submitForm">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
export default {
  name: 'SubjectsAdd',
  props: {
    visible: {
      required: true,
      default: false,
      type: Boolean
    },
    title: {
      default: '新增学科'
    }
  },
  data () {
    return {
      dialogVisible: false,
      formData: {
        subjectName: '',
        isFrontDisplay: true
      },
      rules: {
        subjectName: [
          { required: true, message: '请输入名称', trigger: 'blur' }
        ]
      }
    }
  },
  methods: {
    // 关闭回调
    handleClose (done) {
      this.formData.subjectName = ''
      this.formData.isFrontDisplay = true
      this.$emit('update:visible', false)
      done()
    },
    // 发送审核
    async submitForm () {
      this.$refs.ruleForm.validate((valid) => {
        if (valid) {
          // 触发父组件函数，刷新页面，重新获取数据
          if (this.formData.isFrontDisplay) {
            this.formData.isFrontDisplay = 1
          } else {
            this.formData.isFrontDisplay = 0
          }
          this.$emit('sure', this.formData)
          this.dialogVisible = false
          // 关闭后发送信息给父组件，同步更新父组件visible
          this.$emit('update:visible', false)
        } else {
          return false
        }
      })
    }
  },
  watch: {
    visible (val) {
      this.dialogVisible = val
    },
    id (val) {
      this.formData.id = val
    }
  }
}
</script>

<style scoped lang='less'></style>
